<template>
  <div class="addCraftDialog__container">
    <el-dialog
      v-model="dialogVisible"
      :title="isEdit ? '编辑工艺' : '添加工艺'"
      draggable
      width="70%"
      :before-close="beforeClose"
    >
      <div class="addCraftDialog__body__container">
        <div class="body_button__container">
          <el-button type="primary" @click="addRow">新增工艺步骤</el-button>
        </div>
        <el-table
          ref="singleTableRef"
          border
          :data="tableData"
          highlight-current-row
          style="width: 100%"
          max-height="500"
        >
          <el-table-column label="是否为默认工艺" width="140" align="center">
            <template #default="scope">
              <el-checkbox
                v-if="scope.$index === 0"
                v-model="scope.row.default"
              />
            </template>
          </el-table-column>
          <el-table-column label="工艺步骤" width="230">
            <template #default="scope">
              <el-input-number v-model="scope.row.number" :min="1" />
            </template>
          </el-table-column>
          <el-table-column label="工艺内容">
            <template #default="scope">
              <el-input
                @click.stop.prevent
                v-model="scope.row.content"
                placeholder="请输入工艺内容，必填"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column label="是否需要填写数量">
            <template #default="scope">
              <div>
                <el-radio-group v-model="scope.row.isInputNum" class="ml-4">
                  <el-radio :label="0" size="large">不需要填写</el-radio>
                  <el-radio :label="1" size="large">需要填写</el-radio>
                </el-radio-group>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="160">
            <template #default="scope">
              <el-button
                type="danger"
                @click.stop.prevent="delRow(scope.$index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="confirmDialog">确定</el-button>
          <el-button @click="beforeClose">取消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup name="AddCraftDialog">
import { addCraft, editCraft } from "@/api/craft/index";
import { type CraftItem, CraftContent } from "@/api/craft/types";
const dialogVisible = ref<boolean>(false);
const isEdit = ref<boolean>(false);
const craftId = ref<number>(0);
const emits = defineEmits(["submitSuccess"]);
const tableData = ref<CraftContent[]>([
  {
    default: false,
    number: 1,
    content: "",
    isInputNum: 0,
  },
]);
interface AddParam {
  isEdit: boolean;
  row?: CraftItem;
}
const handleOpen = (data: AddParam) => {
  console.log("data   ", data);
  isEdit.value = data.isEdit;
  console.log("usEdit  ", isEdit.value);
  if (isEdit.value && data.row) {
    let row = data.row;
    craftId.value = data.row.craftId;
    row.content[0].default = row.default == 1 ? true : false;
    tableData.value = [...row.content];
    console.log("编辑测tableData ", tableData.value);
  }
  dialogVisible.value = true;
};
defineExpose({
  handleOpen,
});

// 添加表格
const addRow = () => {
  tableData.value.push({
    default: false,
    number: tableData.value.length + 1,
    content: "",
    isInputNum: 0,
  });
};

// 删除表格
const delRow = (index: number) => {
  tableData.value.splice(index, 1);
};

// 弹窗确定
const confirmDialog = async () => {
  console.log("tableData  ", tableData.value);
  let validatorResult = validator();
  if (!validatorResult) {
    return;
  }

  let params = {
    content: [...tableData.value],
    default: tableData.value[0].default === true ? 1 : 0,
  };
  params.content.forEach((elm) => {
    delete elm.default;
  });
  console.log("params  ", params);
  let res = isEdit.value
    ? await editCraft(craftId.value, params)
    : await addCraft(params);
  if (res) {
    if (!isEdit.value) {
      // 新增
      ElMessage({
        message: "添加成功",
        type: "success",
      });
    } else {
      // 编辑
      ElMessage({
        message: "修改成功",
        type: "success",
      });
    }
    beforeClose(null);
    emits("submitSuccess");
  }
};

// 校验函数
const validator = () => {
  let list = tableData.value;
  let checkoutIndex = list.findIndex((elm) => elm.content == "");
  if (checkoutIndex == -1) {
    return true;
  }
  ElMessage({
    message: `请输入【步骤${checkoutIndex + 1}】的工艺内容`,
    type: "error",
  });
  return false;
};

// 关闭函数
const beforeClose = (done: any) => {
  tableData.value = [
    {
      default: false,
      number: 1,
      content: "",
      isInputNum: 0,
    },
  ];
  craftId.value = 0;
  isEdit.value = false;
  if (typeof done === "function") {
    done();
  } else {
    dialogVisible.value = false;
  }
};
</script>

<style lang="scss" scoped>
.addCraftDialog__container {
  .addCraftDialog__body__container {
    box-sizing: border-box;
    padding-right: 15px;
    max-height: 70vh;
    overflow-y: auto;
    .body_button__container {
      margin-bottom: 10px;
    }
  }
}
</style>
